﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;
using System.IO;
using System.Data.Linq;

namespace QuanLyKhachSan
{
    public partial class frmCheckOut : DevExpress.XtraEditors.XtraForm
    {
        public frmCheckOut()
        {
            InitializeComponent();
        }
        public int cttp_id;
        public frmSoDoPhong frmsodo ;
        DataClassesKhachSanDataContext db = new DataClassesKhachSanDataContext(SystemInfo.pub_ConnString);

        //DataClassesKhachSanDataContext db = new DataClassesKhachSanDataContext();
        static  Decimal tongtiendichvu, tongtienthucan, tongtienphong;
        static int pid, tpid, khid;

        private void gvDichVu_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            //if (e.Column.FieldName == "")
            //{
            //    if (e.RowHandle >= 0)
            //    {
            //        Decimal thanhtien = Decimal.Parse(gvDichVu.GetRowCellValue(e.RowHandle, gridColumn7).ToString()) * Decimal.Parse(gvDichVu.GetRowCellValue(e.RowHandle, gridColumn8).ToString());
            //        e.DisplayText = thanhtien.ToString();
            //    }
            //} 
        }

       
        public Image ByteArrayToImage(byte[] byteArrayIn)
        {
            using (MemoryStream ms = new MemoryStream(byteArrayIn))
            {
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
        }


        void filltrutai()
        {
            var khachhang = (from kh in db.TRU_TAIs
                            where kh.CTTP_ID == cttp_id
                            select kh.KHACH_HANG).ToList ();

            if (khachhang .Count > 0)
            {
                
          

            int x = 10;
            int y = 30;
            int xBt = 0;
            int yBt = 0;

            for (int i = 0; i < khachhang .Count ; i++)
            {
                PictureEdit picKH = new PictureEdit();
                LabelControl lbKH = new LabelControl();
                picKH.Location = new System.Drawing.Point(x, y);
                lbKH.Location = new System.Drawing.Point(x, y + 85);

                x = x + 120;

                if (x + 80 >= panelKH.Width)
                {
                    x = 10;
                    y = y + 110;
                }
                xBt = x;
                yBt = y;

                //khoi tao hinh
                picKH.Name = "picKH" + i.ToString ();
                picKH.Size = new System.Drawing.Size(80, 80);
                picKH.Properties.SizeMode = PictureSizeMode.Stretch;
                if (khachhang[i].KH_HINH != null)
                {
                    picKH.Image = ByteArrayToImage(khachhang[i].KH_HINH.ToArray());
                }
                else
                {
                    picKH.Image = null;
                }
               
                //khoi tao label

                lbKH.Appearance.Options.UseTextOptions = true;
                lbKH.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                lbKH.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.Vertical;
                lbKH.Name = "lbKH" + i.ToString();
                lbKH.Text = khachhang[i].KH_HOTEN;

                panelKH.Controls.Add(picKH);
                panelKH.Controls.Add(lbKH);
                
            }
            //gcKH.DataSource = khachhang;
            }
            else
            {
                groupKhachThue.Visible = false;
            }

        }

        void fillMonAn()
        {
            var monan = from m in db.GOI_THUC_AN_NHANHs
                        where m.CTTP_ID == cttp_id 
                        select new
                        {
                            m.GTAN_ID,
                             m.CTTP_ID ,
                             m.DT_ID,
                             m.G_THOIDIEM ,
                             m.G_SL ,
                             m.G_DONGIA ,
                             m.THUC_UONG_THUC_AN_NHANH .DOI_TUONG .DT_DVI,
                            m.THUC_UONG_THUC_AN_NHANH.DOI_TUONG.DT_TEN,
                            THANHTIEN = m.G_SL * m.G_DONGIA
                        };
            gcThucAn.DataSource = monan;

            if (monan .Count () > 0)
            {
                var sumThucAn = monan.Select(s => s.THANHTIEN).Sum();

                tongtienthucan = sumThucAn;
            }
            
        }
        void fillDichVu()
        {
            var dichvu = from dv in db.SU_DUNGs
                         where dv.SD_CHITIETTPID == cttp_id
                         select new
                         {
                             dv.CHI_TIET_THUE_PHONG.TP_ID,
                             dv.SD_CHITIETTPID,
                             dv.SD_DICHVUID,
                             dv.SD_THOIDIEM,
                             dv.SD_DONGIA,
                             dv.SD_SL,
                             dv.DICH_VU.DV_DONVITINH,
                             dv.DICH_VU.DV_TEN,
                             THANHTIEN = dv.SD_SL * dv.SD_DONGIA,

                         };
            gcDichVu.DataSource = dichvu;

            //var tongtien = (from dv in db.SU_DUNGs 
            //             where dv.SD_CHITIETTPID == cttp_id select
            //             new { THANHTIEN = dv.SD_SL * dv.SD_DONGIA }).Sum ();

            if (dichvu.Count() > 0)
            {
                var sumDichVu = dichvu.Select(s => s.THANHTIEN).Sum();
                tongtiendichvu = sumDichVu;
            }
        }
        void fillKhachHang()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("KH_ID");
            dt.Columns.Add("KH_HOTEN");
            dt.Columns.Add("KH_CMND");

            var khachhang = (db.KHACH_HANGs).OrderByDescending(k => k.KH_ID).ToList ();

           
            for (int i = 0; i < khachhang.Count  ; i++)
            {
                dt.Rows.Add(new object[]
                {
                    khachhang[i].KH_ID ,
                    khachhang [i].KH_HOTEN ,
                    khachhang [i].KH_CMND 
                });
            }
            dt.Rows.Add(new object[]
                {
                    0,
                    "--------Thêm khách hàng mới -----" ,
                    "---------------------------------" 
                });
            leKhachHang.Properties.DataSource = dt;
            leKhachHang.Properties.ValueMember = "KH_ID";
            leKhachHang.Properties.DisplayMember = "KH_HOTEN";
            leKhachHang.ItemIndex = 0;

            leKhachThue.Properties.DataSource = dt;
            leKhachThue.Properties.ValueMember = "KH_ID";
            leKhachThue.Properties.DisplayMember = "KH_HOTEN";
            leKhachThue.ItemIndex = 0;


        }

        private void frmCheckOut_Load(object sender, EventArgs e)
        {
            this.fillKhachHang();
            this.fillDichVu();
            this.fillMonAn();
            this.filltrutai();

            var khachthue = (from k in db.CHI_TIET_THUE_PHONGs
                             where k.CTTP_ID == cttp_id
                             select new
                             {
                                 k.THUE_PHONG.KHACH_HANG.KH_HOTEN,
                                 k.THUE_PHONG.KHACH_HANG.KH_CMND,
                                 k.THUE_PHONG.KHACH_HANG.KH_DIACHI,
                                 k.THUE_PHONG.KHACH_HANG.KH_DIENTHOAI,
                                 k.THUE_PHONG.KHACH_HANG.KH_ID,
                                 k.THUE_PHONG.KHACH_HANG.KH_HINH,
                                 k.P_ID,
                                 k.TP_ID
                             }).Distinct().Single();
            //txtKhachHang.Text = khachthue.KH_HOTEN;
            leKhachHang.EditValue = khachthue.KH_ID;

            if (khachthue.KH_HINH != null)
            {
                picKhachThue.Image = ByteArrayToImage(khachthue.KH_HINH.ToArray());
            }
            else
            {
                picKhachThue.Image = null;
            }

            //txtPhuThu.Text = khachthue .KH_CMND;

            //khid = k.THUE_PHONG.KHACH_HANG.KH_ID;


            var thuephong = (from t in db.CHI_TIET_THUE_PHONGs
                             where t.CTTP_ID == cttp_id
                             select t).Single();
            deNgayDen.EditValue = thuephong.CTTP_NGAYBD;
            deNgayDi.EditValue = DateTime.Now;
            txtDonGia.Text = thuephong.CTTP_DONGIA.ToString();

            pid = int.Parse(thuephong.P_ID.ToString());
            tpid = int.Parse(thuephong.TP_ID.ToString());


            if (thuephong.THUE_PHONG.TP_LOAI_GIA == true)
            {
                TimeSpan ngay = DateTime.Parse(deNgayDi.EditValue.ToString().Substring(0, 10)) - DateTime.Parse(deNgayDen.EditValue.ToString().Substring(0, 10));
                if (ngay.TotalDays < 1)
                {

                    tongtienphong = Decimal.Parse(txtDonGia.Text);
                }
                else
                {
                    tongtienphong = int.Parse(ngay.TotalDays.ToString()) * Decimal.Parse(txtDonGia.Text);
                }
            }
            else
            {
                TimeSpan ngay = DateTime.Parse(deNgayDi.EditValue.ToString()) - DateTime.Parse(deNgayDen.EditValue.ToString());
                tongtienphong = int.Parse(ngay.TotalHours.ToString()) * Decimal.Parse(txtDonGia.Text);
            }
            txtTienPhong.Text = tongtienphong.ToString();
            Decimal phuthu = Decimal.Parse(txtDonGia.Text) * int.Parse(txtPhuThu.EditValue.ToString()) / 100;
            txtTongTien.Text = (tongtiendichvu + tongtienthucan + tongtienphong + phuthu).ToString();

        }

        private void btTraPhong_Click(object sender, EventArgs e)
        {
            try
            {
                this.fillTraPhong();
                XtraMessageBox.Show("Trả phòng thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception)
            {

                throw;
            }
            
           
        }
        void fillTraPhong()
        {
            //kiem tra trang thai phong
            var trangthai = db.PHONGs.Single(t => t.P_ID == pid);

            var datphong = from d in db.CHI_TIET_DAT_PHONGs
                           where d.P_ID == trangthai.P_ID
                           && d.DAT_PHONG.DP_NGAYBD >= DateTime.Today
                           select d;

            if (datphong .Count () > 0)
            {
                trangthai.TT_ID = 6;
            }
            else
            {
                trangthai.TT_ID = 7;
            }
            var chitiet2 = db.CHI_TIET_THUE_PHONGs.Single(c => c.CTTP_ID == cttp_id);

            chitiet2.CTTP_NGAYKT = DateTime.Today;
            chitiet2.CTTP_CHECKOUT = true;

            var chitiet = from c in db.CHI_TIET_THUE_PHONGs where c.TP_ID == tpid select c;

            var thuephong = db.THUE_PHONGs.Single(p => p.TP_ID == tpid);

            thuephong.TP_TONGCONG = thuephong.TP_TONGCONG + Decimal.Parse(txtTongTien.Text);

            if (chitiet.Count() == 1)
            {
      
            }
            else

            {
                //kiem tra chitiet phong cuoi cung duoc check
                var check = chitiet.Select(c => c.CTTP_CHECKOUT == true );

                if (check.Count () <= 1)
                {
                    thuephong.TP_CHECKOUT = true;
                    thuephong.TP_DATRA = true;
                    
                }
                else
                {
                    thuephong.TP_CHECKOUT = false;
                    thuephong.TP_DATRA = false;
                }
               
            }

            //kiem tra tinh trang phong da thanh toan hay chua
            if (checkThanhToan .Checked == true )
            {
                DA_THANH_TOAN thanhtoan = new DA_THANH_TOAN();
                thanhtoan.TP_ID = tpid;
                thanhtoan.DTT_NGAY = DateTime.Now;
                thanhtoan.DTT_SOTIEN = Decimal.Parse(txtTongTien.Text);
                db.DA_THANH_TOANs.InsertOnSubmit(thanhtoan);
            }

            db.SubmitChanges();
        }



        private void frmCheckOut_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmsodo.FillData();
        }

        private void btInHoaDon_Click(object sender, EventArgs e)
        {
            this.fillTraPhong();

            frmInHoaDon hoadon = new frmInHoaDon();
            hoadon.cttp_id = cttp_id;
            hoadon.tp_id = tpid;
            hoadon.phuthu = Convert .ToInt16 ( txtPhuThu.EditValue);
            hoadon.tongtien = Convert.ToDecimal(txtTongTien.EditValue);
            hoadon .tiendichvu = tongtiendichvu ;
            hoadon .thucan = tongtienthucan;
            hoadon.ShowDialog();
        }

        private void txtPhuThu_Leave(object sender, EventArgs e)
        {
            Decimal phuthu = Decimal.Parse(txtDonGia.Text) * int.Parse(txtPhuThu.EditValue.ToString()) / 100;
            txtTongTien.Text = (tongtienphong + phuthu + tongtiendichvu + tongtienthucan ).ToString();
        }

        private void leKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt16 ( leKhachHang.EditValue) == 0)
            {
                   //chưa kiểm tra formclosing
                   frmKhachHang frmKH = new frmKhachHang();
                   frmKH.ShowDialog();
            }
        }

        private void leKhachThue_EditValueChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt16(leKhachThue.EditValue) == 0)
            {
                //chưa kiểm tra formclosing
                frmKhachHang frmKH = new frmKhachHang();
                frmKH.ShowDialog();
            }
            else
            {
                this.filltrutai();
                MessageBox.Show(leKhachThue.EditValue.ToString());
            }
        }

   
    }
}